package com.example.springboot.pdf.controller;

import com.example.springboot.pdf.utils.DateUtils;
import com.example.springboot.pdf.utils.GsonUtils;
import com.example.springboot.pdf.utils.PDFUtils;
import com.example.springboot.pdf.utils.UUIDUtils;
import com.example.springboot.pdf.vo.Constants;
import com.example.springboot.pdf.vo.FileDatalVo;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;


/**
 * @Description: 网吧场所开业
 * @Project: NetBarUnitOpeningController
 * @Author: yanghui
 * @Date 2018-05-28 14:59
 */

@Controller
@RequestMapping(value = "/unitOpen")
@PropertySource(value = "application.properties", ignoreResourceNotFound = true)
public class Word2PdfController {


    /**
     * 图片导入接口
     *
     * @param file
     * @param request
     * @return
     * @throws IllegalStateException
     * @throws IOException
     */
    @ResponseBody
    @SuppressWarnings("deprecation")
    @RequestMapping(value = "/importUpload.do", method = {RequestMethod.GET, RequestMethod.POST}, produces = "text/html;charset=UTF-8")
    public String importUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IllegalStateException, IOException {
        com.example.springboot.pdf.vo.FileDatalVo fileDetailVo = new FileDatalVo();
        if (!file.isEmpty()) {
            // 获取tomcat路径
            String basePath = request.getRealPath(File.separator);
//            String basePath ="F:\\03sourcecode\\trunk\\netbox-platform\\src\\main\\webapp";
            String filename = file.getOriginalFilename();
            filename = UUIDUtils.newGUID() + filename.substring(filename.lastIndexOf("."));
            // 文件真实路径：路径+文件名
            String filePath = basePath + Constants.UNIT_PICTURE_FILE_PATH + File.separator + filename;
            File files = new File(filePath);
            files.delete();
            // 将内存图片写入到磁盘
            file.transferTo(new File(filePath));
            String name = System.currentTimeMillis() + filename;
            fileDetailVo.setFilePath(Constants.UNIT_PICTURE_FILE_PATH + File.separator + filename);
            fileDetailVo.setFileName(name);
            fileDetailVo.setFileSize(String.valueOf(file.getSize()));
            fileDetailVo.setMsg("上传成功");
            fileDetailVo.setResult(true);
        }
        return GsonUtils.parseBeanToJsonHasNull(fileDetailVo);
    }

    /**
     * 导出pdf
     *
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     * @author yanghui
     */
    @RequestMapping(value = "/exportpdf.do", method = {RequestMethod.GET, RequestMethod.POST}, produces = "text/html;charset=UTF-8")
    public String exportPdf(HttpServletResponse response, String UnitCode, HttpServletRequest request) throws UnsupportedEncodingException {
        UnitCode = request.getParameter("UnitCode");

        //String path = request.getSession().getServletContext().getRealPath("/upload/");
        String basePath = request.getRealPath(File.separator);
//        String basePath = "F:\\03sourcecode\\trunk\\netbox-platform\\src\\main\\webapp";
        String filename = "互联网上网服务营业场所模板.pdf";
        String path = basePath + Constants.UNIT_OPENING_PDF_FILE_PATH + File.separator;

        // 指定解析器
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename, "UTF-8"));
        OutputStream os = null;
        PdfStamper ps = null;
        PdfReader reader = null;
        try {
            os = response.getOutputStream();
            // 2 读入pdf表单
            reader = new PdfReader(path + "/" + filename);
            // 3 根据表单生成一个新的pdf
            ps = new PdfStamper(reader, os);
            // 4 获取pdf表单
            AcroFields form = ps.getAcroFields();
            // 5给表单添加中文字体 这里采用系统字体。不设置的话，中文可能无法显示
            BaseFont bf = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",
                    BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            form.addSubstitutionFont(bf);
            // 6查询数据================================================
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("NumNo", DateUtils.formatNoSepDate(new Date()) + new Random().nextInt(900));
            data.put("UnitName", "华景广场");
            data.put("CorporateName", "华景广场");
            data.put("Address", "华景广场");
            data.put("Time", DateUtils.formatDate(new Date()));
            data.put("RealComputers", "  （审核台数2台）");
            data.put("BeginTime", "  2018年08月10日");
            // 7遍历data 给pdf表单表格赋值
            for (String key : data.keySet()) {
                form.setField(key, data.get(key).toString());
            }
            ps.setFormFlattening(true);
            //-----------------------------pdf 添加图片----------------------------------
            System.out.println("===============PDF导出成功=============");
        } catch (Exception e) {
            System.out.println("===============PDF导出失败=============");
            e.printStackTrace();
        } finally {
            try {
                ps.close();
                reader.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * 导出pdf
     *
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     * @author yanghui
     */
    @RequestMapping(value = "/exportpdf2.do", method = {RequestMethod.GET, RequestMethod.POST}, produces = "text/html;charset=UTF-8")
    public String exportPdf2(HttpServletResponse response, String UnitCode, HttpServletRequest request) throws UnsupportedEncodingException {
        UnitCode = request.getParameter("UnitCode");

        //String path = request.getSession().getServletContext().getRealPath("/upload/");
        String basePath = request.getRealPath(File.separator);
//        String basePath = "F:\\03sourcecode\\trunk\\netbox-platform\\src\\main\\webapp";
        String filename = "互联网上网服务营业场所模板.pdf";
        String path = basePath + Constants.UNIT_OPENING_PDF_FILE_PATH + File.separator + filename;

        // 指定解析器
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename, "UTF-8"));

        try {
            // 6查询数据================================================
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("NumNo", DateUtils.formatNoSepDate(new Date()) + new Random().nextInt(900));
            data.put("UnitName", "华景广场");
            data.put("CorporateName", "华景广场");
            data.put("Address", "华景广场");
            data.put("Time", DateUtils.formatDate(new Date()));
            data.put("RealComputers", "  （审核台数2台）");
            data.put("BeginTime", "  2018年08月10日");

            PDFUtils.convertWord2Pdf(response.getOutputStream(), path, data);
            //-----------------------------pdf 添加图片----------------------------------
            System.out.println("===============PDF导出成功=============");
        } catch (Exception e) {
            System.out.println("===============PDF导出失败=============");
            e.printStackTrace();
        }
        return null;
    }


    private Map<String, String> getFlag() {
        Map<String, String> map = new HashMap<>();
        map.put("10", "2" + "&" + "1");
        map.put("30", "3" + "&" + "2");
        map.put("40", "4" + "&" + "3");
        map.put("50", "5" + "&" + "4");
        map.put("130", "6" + "&" + "5");
        return map;
    }
}
